package com.jack.blog.controller;

import com.jack.blog.cache.UserServiceCache;
import com.jack.blog.service.UserService;
import com.jack.blog.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {
    @Value("#{config.host}")
    private String host;
    @Value("#{config.port}")
    private int port;
    @Autowired
    private UserServiceCache userServiceCache;

    @GetMapping("/admin")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String admin(@RequestParam("username")String username, @RequestParam("password")String pwd, Model model){
        try {
            UserVo login = userServiceCache.login(username, pwd);
            model.addAttribute("user",login);
            model.addAttribute("host",host);
            model.addAttribute("port",port);
            return "admin";
        }catch (IllegalArgumentException i){
            model.addAttribute("error",i.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error","run error!");
        }
        model.addAttribute("backUrl","/admin");
        return "error";
    }
}
